package com.dji.system.core;

import javax.swing.JPopupMenu;
import javax.swing.UIManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dji.bean.Autowired;
import com.dji.bean.Compoment;
import com.dji.common.utils.SystemUtils;
import com.dji.swing.model.FingerLinster;
import com.dji.swing.view.BrowserItemView;
import com.dji.swing.view.Windows;

/**
 * 环境初始化
 * 
 * @author xinlin.wang
 *
 */
@Compoment
public class SystemInit {
	private final static Logger log = LoggerFactory.getLogger(SystemInit.class);
	@Autowired
	private static Windows window;
	@Autowired
	private static BrowserItemView browser;
	@Autowired
	private static NIOClient nioClient;
	@Autowired
	private static FingerLinster fingerLinster;

	public static void initEnv() {
		try {
			initSysEnv();
			initNIOSocket();
			initSwingView();
		} catch (Exception e) {
			log.error("系统异常", e);
			System.exit(-1);
		}
	}

	/**
	 * 系统环境参数初始化
	 * 
	 * @throws Exception
	 */
	private static void initSysEnv() throws Exception {
		log.debug("开始加载系统环境变量");
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		System.setProperty("apple.laf.useScreenMenuBar", "true");
		System.setProperty("com.apple.mrj.application.apple.menu.about.name", "any question ,main wxl_1987@yeah.net");
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		JPopupMenu.setDefaultLightWeightPopupEnabled(false);
	}

	/**
	 * swing视图初始化
	 */
	private static void initSwingView() {
		log.debug("开始初始化swing组件");
		window.add(browser);
		window.setVisible(true);
	}

	/**
	 * 浏览器页面初始化
	 */
	public static void initBrow() {
		StringBuilder mainPath = new StringBuilder("file:///");
		mainPath.append(SystemUtils.getProjectPath());
		if (mainPath.toString().endsWith("/")) {
			mainPath.append("html/login.html");
		} else {
			mainPath.append("/html/login.html");
		}
		browser.getBrowser().loadURL(mainPath.toString());
	}

	/**
	 * NIO组件初始化
	 */
	private static void initNIOSocket() {
		log.debug("开始初始化NIO组件");
		nioClient.connect();
	}

	/**
	 * 开启指纹线程
	 */
	public static void fingerSearchStart() {
		if (!fingerLinster.isAlive()) {
			fingerLinster.start();
		}
	}

	/**
	 * 系统退出
	 */
	public static void exit() {
		try {
			// socket关闭
			// 指纹usb，线程关闭
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统退出发生异常", e);
		} finally {
			log.debug("系统退出");
			System.exit(0);
		}
	}

}
